package com.lsh.ofc.core.wumartbasic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.ofc.core.constant.Constants;
import com.lsh.ofc.proxy.context.WumartBasicContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.Map;

/**
 * Project Name: lsh-ofc
 * Author: panxudong
 * 北京链商电子商务有限公司
 * Desc: 类功能描述
 * Package Name: com.lsh.ofc.proxy.handler
 * Time: 2017-07-27 下午3:21
 *
 * @author peter
 */
@Service
@Slf4j
public class WumartBasicCustomerStrategy extends AbstractWumartBasicStrategy {

    @Override
    public boolean validate(WumartBasicContext context) {
        log.info("redis customer context is " + JSON.toJSONString(context));
        if (context.size() == 3) {
            if (super.basicValidate(context)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public String getConfigKey(WumartBasicContext context) {
        Integer cusType = (Integer) context.getProperty(WumartBasicContext.CUSTYPE);
        Integer region = (Integer) context.getProperty(WumartBasicContext.REGION);
        return this.buildCusConfigKey(region, cusType);
    }

    private String buildCusConfigKey(Integer region, Integer cusType) {
        String redisKey = MessageFormat.format(Constants.OFC_SUPPLIER_CUS_CONFIG, String.valueOf(region), String.valueOf(cusType));
        return redisKey;
    }

    @Override
    public String getConfigValue(WumartBasicContext context) {
        Map<String, String> configs = super.getConfig(context);
        log.info("redis customer configs is " + JSON.toJSONString(configs));
        if (configs.isEmpty()) {
            return null;
        }
        String config = configs.entrySet().iterator().next().getValue();
        log.info("redis customer config is " + JSON.toJSONString(config));
        if (!StringUtils.hasText(config)) {
            return null;
        }
        JSONObject configObject = JSONObject.parseObject(config);
        log.info("redis customer configObject is " + configObject.toJSONString());
        String key = String.valueOf(context.getProperty(WumartBasicContext.PARAM));
        log.info("redis customer configObject key " + key);
        return configObject.getString(key);
    }

}
